package com.sl.biz.core.config;/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */


import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.sl.biz.core.runner.loader.DatabaseProcessPluginLoader;
import com.sl.biz.core.websocket.ProcessWevSocketHandler;
import com.sl.biz.modular.job.service.JobConfigBizService;
import com.sl.biz.modular.restapi.handler.ApiHandler;
import com.sl.core.engine.ProcessEngine;
import com.sl.core.engine.datasource.DataSourceManager;
import com.sl.core.engine.datasource.DataSourceQueryService;
import com.sl.core.engine.exchange.CamelConfig;
import com.sl.core.engine.loader.DefaultProcessSourceFileLoader;
import com.sl.core.engine.loader.ProcessSourceFileLoader;
import com.sl.core.engine.log.store.LoggerStoreFactory;
import com.sl.core.engine.plugin.ProcessPluginLoaderManager;
import com.sl.core.job.ProcessJobConfig;
import com.sl.core.workflow.WorkFlowEngine;
import com.sl.core.workflow.listener.IWorkFlowStatusService;
import com.sl.core.workflow.listener.WorkflowPipelineListener;
import lombok.RequiredArgsConstructor;
import org.apache.camel.CamelContext;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import java.util.Map;


@Configuration
@EnableWebSocket
@RequiredArgsConstructor
public class BizConfigure implements WebSocketConfigurer {

    private final ProcessWevSocketHandler processWevSocketHandler;


    @Bean
    public CommandLineRunner commandLineRunner(DynamicDataSourceProperties dataSourceProperties, DatabaseProcessPluginLoader databaseProcessPluginLoader,
                                               CamelContext camelContext, ApiHandler restApiHandler,
                                               JobConfigBizService jobConfigBizService,
                                               DataSourceQueryService dataSourceQueryService,
                                               ProcessSourceFileLoader processSourceFileLoader,
                                               IWorkFlowStatusService workFlowStatusService) {
        return (r) -> {
            //插件从数据库中加载
            ProcessPluginLoaderManager.INSTANCE.registry(databaseProcessPluginLoader);
            ProcessEngine.INSTANCE.init();
            WorkFlowEngine.INSTANCE.init();

            Map<String, DataSourceProperty> datasource = dataSourceProperties.getDatasource();
            DataSourceProperty dataSourceProperty = datasource.get(dataSourceProperties.getPrimary());
            DataSourceProperties dataSource = new DataSourceProperties();
//            dataSource.setGenerateUniqueName(false);
            dataSource.setName(dataSourceProperty.getPoolName());
            dataSource.setType(dataSourceProperty.getType());
            dataSource.setDriverClassName(dataSourceProperty.getDriverClassName());
            dataSource.setUrl(dataSourceProperty.getUrl());
            dataSource.setUsername(dataSourceProperty.getUsername());
            dataSource.setPassword(dataSourceProperty.getPassword());
            ProcessJobConfig.INSTANCE.init(dataSource, (jobId) -> {
                return jobConfigBizService.execute(jobId);
            });
            DataSourceManager.INSTANCE.init(dataSourceQueryService);
            jobConfigBizService.init();
            CamelConfig.INSTANCE.init(camelContext, restApiHandler);
            LoggerStoreFactory.INSTANCE.initDb("default");

            DefaultProcessSourceFileLoader.INSTANCE = processSourceFileLoader;
            WorkflowPipelineListener.SERVICE = workFlowStatusService;
            //::启动服务端
//            SocketD.createServer("sd:tcp").config(c -> c.port(8602))
//                    .listen(new SimpleListener() {
//                        @Override
//                        public void onMessage(Session session, Message message) throws IOException {
//                            //打印
//                            System.out.println(message);
//                        }
//                    })
//                    .start();
        };
    }


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(processWevSocketHandler, "/ws")
                .setAllowedOrigins("*");
    }
}
